//
//  MessageMapViewController.m
//  JiuLe
//
//  Created by xcq on 15/11/30.
//  Copyright © 2015年 Fine. All rights reserved.
//
#import <BMKGeometry.h>
#import "MessageMapViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <AMapSearchKit/AMapSearchKit.h>

@interface MessageMapViewController () <MAMapViewDelegate,AMapSearchDelegate>
@property (weak, nonatomic) IBOutlet UIView *mapParentView;
@property (weak, nonatomic) IBOutlet UILabel *location;
@property (weak, nonatomic) IBOutlet UILabel *event;
@property (weak, nonatomic) IBOutlet UILabel *xueyangNum;
@property (weak, nonatomic) IBOutlet UILabel *xueyangAbout;
@property (weak, nonatomic) IBOutlet UILabel *xinlvNum;
@property (weak, nonatomic) IBOutlet UILabel *xinlvAbout;
@property (weak, nonatomic) IBOutlet UITextView *advice;
@property (strong, nonatomic) UIButton *testBtn;
@property (strong, nonatomic) MACircle *circle;
@property (strong, nonatomic) MAMapView *mapView;
@property (strong, nonatomic) AMapSearchAPI *search;
@property (strong, nonatomic) AMapReGeocodeSearchRequest *regeo;
@property (strong, nonatomic) CLGeocoder *geo;
@property (assign, nonatomic) BOOL back;

@end
//requestLocationWithReGeocode
@implementation MessageMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"预警详情";
    [self showNavgationWithLeftItemWithTitle:@"返回"];
    _back = NO;
    [self requestEarlyWarningDetails];
}

- (void)requestEarlyWarningDetails{
    [SVProgressHUD showWithStatus:@"预警信息.." maskType:SVProgressHUDMaskTypeClear];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [dict setObject:[NSNumber numberWithInt:[self.warningID intValue]] forKey:@"warn_id"];
    [[BaseDataRequest alloc] getEarlyWarningDetailsData:dict WithBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        _back = YES;
        if ([status isEqualToString:@"0"]) {
            NSMutableArray *arrResult = [NSMutableArray arrayWithArray:[responseObject objectForKey:@"result"]];
            NSMutableDictionary *dict = arrResult.firstObject;
            _model = [[MessageModel alloc] init];
            _model.latitude = [dict objectForKey:@"latitude"];
            _model.longitude = [dict objectForKey:@"longitude"];
            _model.msgtime = self.time;
            _model.msgtitle = self.heading;
             [self initAlsoSetCoordinate];
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW(@"获取预警详情失败");
            }
        }
    }];
}


- (void)initAlsoSetCoordinate {
    [self setUpMapView];
    CLLocationCoordinate2D coordina;
    _warningTitle.text = [self.title stringByAppendingString:@"位置"];
    if ( (_model.latitude && [_model.latitude doubleValue] > 0.0) && ([_model.longitude doubleValue] > 0.f && _model.longitude)) {
        coordina = CLLocationCoordinate2DMake([_model.latitude doubleValue], [_model.longitude doubleValue]);
        MyAnnotation *annotation = [[MyAnnotation alloc] initWithCoordinates:coordina title:@"watchCoor" subTitle:@"" identifer:@"watch"];
        _circle = [MACircle circleWithCenterCoordinate:coordina  radius:150];
        [_mapView addOverlay:_circle];
        [_mapView addAnnotation:annotation];
        [_mapView setCenterCoordinate:coordina];
        
    } else {
        [_mapView setHidden:YES];
    }
    _event.text = [NSString stringWithFormat:@"您于%@发生了%@",_model.msgtime,_model.msgtitle];
}

//实现逆地理编码的回调函数
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if(response.regeocode != nil)
    {
        _location.text = [[[[[response.regeocode.addressComponent.province stringByAppendingString:response.regeocode.addressComponent.city] stringByAppendingString:response.regeocode.addressComponent.district] stringByAppendingString:response.regeocode.addressComponent.building] stringByAppendingString:response.regeocode.addressComponent.streetNumber.street] stringByAppendingString:@"附近"];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (_mapView) {
        _mapView.delegate = self;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_mapView.delegate != nil) {
        _mapView.showsUserLocation = NO;
        _mapView.delegate = nil;
    }
}



- (void)setUpMapView {
    if (_mapView==nil) {
        _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0,
                                                               0,
                                                               CGRectGetWidth(_mapParentView.bounds),
                                                               CGRectGetHeight(_mapParentView.bounds))];
        _mapView.delegate = self;
        [_mapView setZoomLevel:17.0f animated:YES];
        [_mapParentView addSubview:_mapView];
    }
}

- (MAAnnotationView*)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    MAAnnotationView * result = nil;
    if([annotation isKindOfClass:[MyAnnotation class]])
    {
        return  [self mapViewWithAnnotationView:annotation];
    }
    static NSString *annotationStr = @"MAPinAnnotationView";
    MAPinAnnotationView *annotationView = (MAPinAnnotationView *)[_mapView dequeueReusableAnnotationViewWithIdentifier:annotationStr];
    if (annotationView == nil) {
        annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationStr];
        [annotationView setCanShowCallout:YES];
    }
    annotationView.opaque = NO;
    annotationView.animatesDrop = YES;
    annotationView.draggable = YES;
    annotationView.selected = YES;
    annotationView.calloutOffset = CGPointMake(15, 15);
    annotationView.image = [UIImage imageNamed:@"detail_p"];
    result = annotationView;
    return result;
}

- (MAAnnotationView *)mapViewWithAnnotationView:(id<MAAnnotation>)annotation {
     MAAnnotationView * result = nil;
    MyAnnotation * senderAnnotation = (MyAnnotation *)annotation;
    MAPinAnnotationView * annotationView = (MAPinAnnotationView *)[_mapView dequeueReusableAnnotationViewWithIdentifier:senderAnnotation.identifier];
    if(annotationView == nil)
    {
        annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:senderAnnotation reuseIdentifier:senderAnnotation.identifier];
        [annotationView setCanShowCallout:YES];
    }
    annotationView.opaque = NO;
    annotationView.animatesDrop = YES;
    annotationView.draggable = YES;
    annotationView.selected = YES;
    annotationView.calloutOffset = CGPointMake(15, 15);
    annotationView.image = [UIImage imageNamed:@"detail_p2"];
    result = annotationView;
    
    return result;
}

- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MACircle class]]) {
        MACircleView *overlayView = [[MACircleView alloc] initWithOverlay:overlay];
        overlayView.lineWidth = 1;
        overlayView.fillColor = [RGB(231, 189, 189) colorWithAlphaComponent:0.5];
        overlayView.strokeColor = [RGB(231, 189, 189) colorWithAlphaComponent:0.5];
        return overlayView;
    }
    return nil;
}

//传两个坐标求出中心点并转换为地图的坐标
- (void)convertCenterCoordinate2D:(CLLocationCoordinate2D)firstCoor lastCoor:(CLLocationCoordinate2D)lastCoor {
    //取出当前位置的坐标
    CGPoint phonePoint = [_mapView convertCoordinate:firstCoor toPointToView:self.view];
    CGPoint watchPoint = [_mapView convertCoordinate:lastCoor toPointToView:self.view];
    CGPoint centerPoint = CGPointMake(fabs(phonePoint.x - watchPoint.x) / 2 + fmin(phonePoint.x, watchPoint.x), fabs(phonePoint.y - watchPoint.y) / 2 + fmin(phonePoint.y, watchPoint.y));
    CLLocationCoordinate2D centerCoor = [_mapView convertPoint:centerPoint toCoordinateFromView:self.view];
    [_mapView setCenterCoordinate:centerCoor];
    
    CLLocationCoordinate2D topLeftCoord;
    topLeftCoord.latitude = -90;
    topLeftCoord.longitude = 180;
    
    CLLocationCoordinate2D bottomRightCoord;
    bottomRightCoord.latitude = 90;
    bottomRightCoord.longitude = -180;
    for(id<MAAnnotation> annotation in _mapView.annotations) {
        topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
        topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
        bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
        bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
    }
    MACoordinateRegion region;
    region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
    region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.7;
    
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.7;
    
    region = [_mapView regionThatFits:region];
    [_mapView setRegion:region animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)backTo{
    if (_back) {
        [super backTo];
    }else{
        NSLog(@"你点我干嘛");
    }
}

@end
